{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from numpy import genfromtxt\n",
    "import matplotlib.pyplot as plt  \n",
    "from mpl_toolkits.mplot3d import Axes3D  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 读入数据 \n",
    "data = genfromtxt(r\"Delivery.csv\",delimiter=',')\n",
    "print(data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 切分数据\n",
    "x_data = data[:,:-1]\n",
    "y_data = data[:,-1]\n",
    "print(x_data)\n",
    "print(y_data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 学习率learning rate\n",
    "lr = 0.0001\n",
    "# 参数\n",
    "theta0 = 0\n",
    "theta1 = 0\n",
    "theta2 = 0\n",
    "# 最大迭代次数\n",
    "epochs = 1000\n",
    "\n",
    "# 最小二乘法\n",
    "def compute_error(theta0, theta1, theta2, x_data, y_data):\n",
    "    totalError = 0\n",
    "    for i in range(0, len(x_data)):\n",
    "        totalError += (y_data[i] - (theta1 * x_data[i,0] + theta2*x_data[i,1] + theta0)) ** 2\n",
    "    return totalError / float(len(x_data))\n",
    "\n",
    "def gradient_descent_runner(x_data, y_data, theta0, theta1, theta2, lr, epochs):\n",
    "    # 计算总数据量\n",
    "    m = float(len(x_data))\n",
    "    # 循环epochs次\n",
    "    for i in range(epochs):\n",
    "        theta0_grad = 0\n",
    "        theta1_grad = 0\n",
    "        theta2_grad = 0\n",
    "        # 计算梯度的总和再求平均\n",
    "        for j in range(0, len(x_data)):\n",
    "            theta0_grad += -(1/m) * (y_data[j] - (theta1 * x_data[j,0] + theta2*x_data[j,1] + theta0))\n",
    "            theta1_grad += -(1/m) * x_data[j,0] * (y_data[j] - (theta1 * x_data[j,0] + theta2*x_data[j,1] + theta0))\n",
    "            theta2_grad += -(1/m) * x_data[j,1] * (y_data[j] - (theta1 * x_data[j,0] + theta2*x_data[j,1] + theta0))\n",
    "        # 更新b和k\n",
    "        theta0 = theta0 - (lr*theta0_grad)\n",
    "        theta1 = theta1 - (lr*theta1_grad)\n",
    "        theta2 = theta2 - (lr*theta2_grad)\n",
    "    return theta0, theta1, theta2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(\"Starting theta0 = {0}, theta1 = {1}, theta2 = {2}, error = {3}\".\n",
    "      format(theta0, theta1, theta2, compute_error(theta0, theta1, theta2, x_data, y_data)))\n",
    "print(\"Running...\")\n",
    "theta0, theta1, theta2 = gradient_descent_runner(x_data, y_data, theta0, theta1, theta2, lr, epochs)\n",
    "print(\"After {0} iterations theta0 = {1}, theta1 = {2}, theta2 = {3}, error = {4}\".\n",
    "      format(epochs, theta0, theta1, theta2, compute_error(theta0, theta1, theta2, x_data, y_data)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "ax = plt.figure().add_subplot(111, projection = '3d') \n",
    "ax.scatter(x_data[:,0], x_data[:,1], y_data, c = 'r', marker = 'o', s = 100) #点为红色三角形  \n",
    "x0 = x_data[:,0]\n",
    "x1 = x_data[:,1]\n",
    "# 生成网格矩阵\n",
    "x0, x1 = np.meshgrid(x0, x1)\n",
    "z = theta0 + x0*theta1 + x1*theta2\n",
    "# 画3D图\n",
    "ax.plot_surface(x0, x1, z)\n",
    "#设置坐标轴  \n",
    "ax.set_xlabel('Miles')  \n",
    "ax.set_ylabel('Num of Deliveries')  \n",
    "ax.set_zlabel('Time')  \n",
    "  \n",
    "#显示图像  \n",
    "plt.show()  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [default]",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
